package com.ljx.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljx.search.config.ApiException;
import com.ljx.search.service.SearchService;
import com.ljx.search.util.HttpUtils;
import com.ljx.search.vo.req.SearchParam;
import com.ljx.search.vo.resp.AuthResp;
import com.ljx.search.vo.resp.PageResp;
import com.ljx.search.vo.resp.SearchResp;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-04  21:44
 */
@Service
public class SearchServiceImpl implements SearchService {


    @Override
    public PageResp<SearchResp> search(SearchParam param) {
        if (Objects.isNull(param)) {
            throw new ApiException("参数不能为空");
        }

        AuthResp authResp = tryToGetToken(param);

        return tryToGetSearchData(param, authResp);
    }

    private AuthResp tryToGetToken(SearchParam param) {
        String host = "https://connect.zhihuiya.com";
        String path = "/oauth/token";

        Map headers = new HashMap();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        String auth = param.getClientId() + ":" + param.getClientSecret();
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        headers.put("Authorization", "Basic " + encodedAuth);

        Map querys = new HashMap();
        querys.put("grant_type", "client_credentials");

        try {
            HttpResponse response = HttpUtils.doPost(host, path, "post", headers, null, querys);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            return JSONObject.parseObject(JSON.parseObject(responseBody).get("data").toString(), AuthResp.class);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new ApiException("获取token发生错误");
        }

    }

    private PageResp<SearchResp> tryToGetSearchData(SearchParam param, AuthResp authResp) {
        if (Objects.isNull(authResp)) {
            return new PageResp<>();
        }
        String host = "https://connect.zhihuiya.com";
        String path = "/search/patent/query-search-patent";

        Map headers = new HashMap();
        headers.put("Content-Type", "application/json");
        headers.put("authorization", "Bearer " + authResp.getToken());

        Map querys = new HashMap();
        querys.put("apikey", param.getClientId());
        Long currPage = (param.getPage() - 1) * param.getSize();
        JSONObject dataBody;
        if (StringUtils.isEmpty(param.getKeyword())) {
            throw new ApiException("参数不能为空");
        }
        dataBody = (JSONObject) JSON.parse("{\"sort\":[{\"field\":\"SCORE\",\"order\":\"DESC\"}],\"limit\":"
                + param.getSize() + ",\"offset\":" + currPage + ",\"stemming\":0,\"query_text\":\"" + param.getKeyword() + "\"," +
                "\"collapse_by\":\"PBD\",\"collapse_type\":\"ALL\",\"collapse_order\":\"LATEST\",\"collapse_order_authority\"" +
                ":[\"CN\",\"US\",\"EP\",\"JP\",\"KR\"]}");


        try {
            HttpResponse response = HttpUtils.doPost(host, path, null, headers, querys, dataBody.toJSONString());
            String responseStr = EntityUtils.toString(response.getEntity());
            JSONObject data = (JSONObject) JSON.parseObject(responseStr).get("data");

            PageResp<SearchResp> resp = new PageResp<>();
            resp.setData(JSON.parseArray(data.getString("results"), SearchResp.class));
            resp.setTotalSize(Long.valueOf(data.getString("total_search_result_count")));
            return resp;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new ApiException("获取查询列表出错");

        }

    }
}
